package com.zhaowt.event.listeners;

import com.zhaowt.event.MyLoginEvent;
import com.zhaowt.mapper.SysLogininforMapper;
import com.zhaowt.pojo.SysLogininfor;
import com.zhaowt.util.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * created by 赵文韬 on 2023/1/1 15:34
 */
@EnableAsync
@Component
public class LoginEventListener {
    private SysLogininforMapper sysLogininforMapper;
    @Autowired
    public void setSysLogininforMapper(SysLogininforMapper sysLogininforMapper) {
        this.sysLogininforMapper = sysLogininforMapper;
    }
    @EventListener
    public void onEvent(MyLoginEvent event){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        /*CompletableFuture.runAsync(()->{*/
            HttpServletRequest request = requestAttributes.getRequest();
            String ip = RequestUtil.getRemoteHost(request);
            String locationByIp = RequestUtil.getLocationByIp(ip);
            Map<String, Object> parameterMap = RequestUtil.getParameterMap(request);
            Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);
            String os = osAndBrowserInfo.get("os");
            String browser = osAndBrowserInfo.get("browser");
            //todo将信息保存到数据库
            SysLogininfor logininfor = new SysLogininfor();
            logininfor.setOs(os);
            logininfor.setLoginTime(new Date());
            logininfor.setLoginLocation(locationByIp);
            logininfor.setIpaddr(ip);
            logininfor.setBrowser(browser);
            logininfor.setLoginName(event.getUsername());
            switch (event.getResult()){
                case FAIL:
                    logininfor.setMsg("登陆失败");
                    logininfor.setStatus("1");
                    break;
                case SUCCESS:
                    logininfor.setMsg("登陆成功");
                    logininfor.setStatus("0");
                    break;
            }
            sysLogininforMapper.addLogininfor(logininfor);
        /*});*/

    }
}
